package com.rocky.component.elasticsearch.service;

import com.rocky.component.elasticsearch.enums.RockyESPropertyEnum;
import lombok.RequiredArgsConstructor;
import org.elasticsearch.ElasticsearchException;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.action.support.master.AcknowledgedResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.PutMappingRequest;
import org.elasticsearch.rest.RestStatus;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author rocky
 * date 2025-08-09
 * Description:
 */
@RequiredArgsConstructor
public class RockyIndexService {

    private final Logger logger = LoggerFactory.getLogger(RockyIndexService.class);

    private final RestHighLevelClient restHighLevelClient;

    public boolean delete(String index) {
        DeleteIndexRequest deleteIndexRequest = new DeleteIndexRequest(index);

        AcknowledgedResponse acknowledgedResponse;
        try {
            acknowledgedResponse = restHighLevelClient.indices().delete(deleteIndexRequest, RequestOptions.DEFAULT);
        } catch (ElasticsearchException e) {
            if (e.status() == RestStatus.NOT_FOUND) {
                logger.warn("Rocky elasticsearch index [" + index + "] have been deleted or not found", e);
                return true;
            }

            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        if (acknowledgedResponse.isAcknowledged()) {
            logger.info("Rocky elasticsearch index [" + index + "] deleted succeed");
        }

        return acknowledgedResponse.isAcknowledged();
    }

    public boolean updateMapping(String index, Map<String, Object> propertiesMap) {
        Map<String, Object> mapping = new HashMap<>();
        mapping.put(RockyESPropertyEnum.PROPERTIES.getCode(), propertiesMap);

        PutMappingRequest putMappingRequest = new PutMappingRequest(index).source(mapping);

        AcknowledgedResponse acknowledgedResponse;
        try {
            acknowledgedResponse = restHighLevelClient.indices().putMapping(putMappingRequest, RequestOptions.DEFAULT);
        } catch (ElasticsearchException e) {
            if (e.status() == RestStatus.NOT_FOUND) {
                logger.error("Rocky elasticsearch index [" + index + "] mapping put error, because this index have been deleted or not found", e);
                return false;
            }

            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        if (acknowledgedResponse.isAcknowledged()) {
            logger.info("Rocky elasticsearch index [" + index + "] mapping put succeed");
        }

        return acknowledgedResponse.isAcknowledged();
    }

}
